// 事件处理JavaScript文件

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function () {
    // 加载基础信息和连接列表
    loadUserInfo();
    loadConnectionOptions();

    // 确保连接选择框默认不选择任何连接，并确保测试按钮可用
    setTimeout(() => {
        const connectionSelect = document.getElementById('connectionSelect');
        const testBtn = document.getElementById('testConnectionBtn');

        if (connectionSelect) {
            connectionSelect.value = '';
            onConnectionSelectChange();
        }

        // 确保测试连接按钮可用
        if (testBtn) {
            testBtn.disabled = false;
            testBtn.textContent = '测试连接';
        }
    }, 100);

    // 不自动测试连接，让用户手动选择和测试
    loadConnections();

    // 检查用户权限
    setTimeout(checkUserPermissions, 200);
});

// 处理新建数据库表单提交
document.addEventListener('DOMContentLoaded', function () {
    const createDatabaseForm = document.getElementById('createDatabaseForm');
    if (createDatabaseForm) {
        createDatabaseForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitDatabaseBtn');
            const originalText = submitBtn.textContent;

            // 获取表单数据
            const formData = new FormData(this);
            const databaseName = formData.get('databaseName').trim();
            const collectionName = formData.get('collectionName').trim() || 'test';

            // 验证数据库名称
            if (!databaseName) {
                alert('数据库名称不能为空！');
                return;
            }

            // 验证数据库名称格式（MongoDB数据库名称规则）
            if (!/^[a-zA-Z0-9_-]+$/.test(databaseName)) {
                alert('数据库名称只能包含字母、数字、下划线和连字符！');
                return;
            }

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '创建中...';

            try {
                const connectionSelect = document.getElementById('connectionSelect');
                const selectedConnectionId = connectionSelect.value;

                let url = '/api/databases/create';
                if (selectedConnectionId) {
                    url += `?connection_id=${selectedConnectionId}`;
                }

                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        database_name: databaseName,
                        collection_name: collectionName
                    })
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert(`数据库 "${databaseName}" 创建成功！\n集合 "${collectionName}" 已创建。`);
                    closeCreateDatabaseModal();
                    loadDatabases(); // 刷新数据库列表
                    loadDatabaseOptions(); // 刷新数据库选择框
                } else {
                    alert(`创建失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                console.error('创建数据库失败:', error);
                alert(`创建失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理新增用户表单提交
document.addEventListener('DOMContentLoaded', function () {
    const addUserForm = document.getElementById('addUserForm');
    if (addUserForm) {
        addUserForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitUserBtn');
            const originalText = submitBtn.textContent;

            // 获取表单数据
            const formData = new FormData(this);
            const targetDatabase = formData.get('targetDatabase');
            const username = formData.get('newUsername');
            const password = formData.get('newPassword');
            const confirmPassword = formData.get('confirmPassword');

            // 验证密码
            if (password !== confirmPassword) {
                alert('密码和确认密码不匹配！');
                return;
            }

            if (password.length < 6) {
                alert('密码长度至少6位！');
                return;
            }

            // 收集角色信息
            const roles = [];
            const roleItems = document.querySelectorAll('.role-item');

            for (let item of roleItems) {
                const roleDatabaseSelect = item.querySelector('select[name="roleDatabase"]');
                const roleNameSelect = item.querySelector('select[name="roleName"]');

                if (roleDatabaseSelect && roleNameSelect) {
                    const roleDatabase = roleDatabaseSelect.value;
                    const roleName = roleNameSelect.value;

                    if (roleDatabase && roleName) {
                        roles.push({
                            db: roleDatabase,
                            role: roleName
                        });
                    }
                }
            }

            if (roles.length === 0) {
                alert('请至少添加一个角色！');
                return;
            }

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '创建中...';

            try {
                const connectionSelect = document.getElementById('connectionSelect');
                const selectedConnectionId = connectionSelect.value;

                let url = '/api/users/create';
                if (selectedConnectionId) {
                    url += `?connection_id=${selectedConnectionId}`;
                }

                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        database: targetDatabase,
                        username: username,
                        password: password,
                        roles: roles
                    })
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('用户创建成功！');
                    closeAddUserModal();
                    loadUsers(); // 刷新用户列表
                } else {
                    alert(`创建失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`创建失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理编辑用户表单提交
document.addEventListener('DOMContentLoaded', function () {
    const editUserForm = document.getElementById('editUserForm');
    if (editUserForm) {
        editUserForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitEditUserBtn');
            const originalText = submitBtn.textContent;

            if (!currentEditUser) {
                alert('没有选择要编辑的用户！');
                return;
            }

            // 获取表单数据
            const formData = new FormData(this);
            const newPassword = formData.get('editNewPassword');
            const confirmPassword = formData.get('editConfirmPassword');

            // 验证密码（如果提供了新密码）
            if (newPassword || confirmPassword) {
                if (newPassword !== confirmPassword) {
                    alert('新密码和确认密码不匹配！');
                    return;
                }

                if (newPassword.length < 6) {
                    alert('密码长度至少6位！');
                    return;
                }
            }

            // 收集角色信息
            const roles = [];
            const roleItems = document.querySelectorAll('#editRolesContainer .role-item');

            for (let item of roleItems) {
                const roleDatabaseSelect = item.querySelector('select[name="editRoleDatabase"]');
                const roleNameSelect = item.querySelector('select[name="editRoleName"]');

                if (roleDatabaseSelect && roleNameSelect) {
                    const roleDatabase = roleDatabaseSelect.value;
                    const roleName = roleNameSelect.value;

                    if (roleDatabase && roleName) {
                        roles.push({
                            db: roleDatabase,
                            role: roleName
                        });
                    }
                }
            }

            if (roles.length === 0) {
                alert('请至少添加一个角色！');
                return;
            }

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '更新中...';

            try {
                const connectionSelect = document.getElementById('connectionSelect');
                const selectedConnectionId = connectionSelect.value;

                let url = `/api/users/${encodeURIComponent(currentEditUser.username)}/update`;
                if (selectedConnectionId) {
                    url += `?connection_id=${selectedConnectionId}`;
                }

                const requestBody = {
                    database: currentEditUser.database,
                    roles: roles
                };

                // 只有在提供新密码时才包含密码字段
                if (newPassword) {
                    requestBody.password = newPassword;
                }

                const response = await fetch(url, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('用户更新成功！');
                    closeEditUserModal();
                    loadUsers(); // 刷新用户列表
                } else {
                    alert(`更新失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`更新失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理修改密码表单提交
document.addEventListener('DOMContentLoaded', function () {
    const changePasswordForm = document.getElementById('changePasswordForm');
    if (changePasswordForm) {
        changePasswordForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitChangePasswordBtn');
            const originalText = submitBtn.textContent;

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '修改中...';

            try {
                const formData = new FormData(this);
                const data = {
                    current_password: formData.get('currentPassword'),
                    new_password: formData.get('newPassword'),
                    confirm_password: formData.get('confirmNewPassword')
                };

                const response = await fetch('/api/users/change-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('密码修改成功！');
                    closeChangePasswordModal();
                } else {
                    alert(`修改失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`修改失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理个人信息表单提交
document.addEventListener('DOMContentLoaded', function () {
    const profileForm = document.getElementById('profileForm');
    if (profileForm) {
        profileForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitProfileBtn');
            const originalText = submitBtn.textContent;

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '更新中...';

            try {
                const formData = new FormData(this);
                const data = {
                    email: formData.get('profileEmail'),
                    full_name: formData.get('profileFullName')
                };

                const response = await fetch('/api/users/profile', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('个人信息更新成功！');
                    closeProfileModal();
                } else {
                    alert(`更新失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`更新失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理新增系统用户表单提交
document.addEventListener('DOMContentLoaded', function () {
    const createSystemUserForm = document.getElementById('createSystemUserForm');
    if (createSystemUserForm) {
        createSystemUserForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitSystemUserBtn');
            const originalText = submitBtn.textContent;

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '创建中...';

            try {
                const formData = new FormData(this);
                const data = {
                    username: formData.get('systemUsername'),
                    password: formData.get('systemPassword'),
                    email: formData.get('systemEmail'),
                    full_name: formData.get('systemFullName'),
                    is_admin: formData.get('systemIsAdmin') === 'on'
                };

                const response = await fetch('/api/system-users/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('用户创建成功！');
                    closeCreateSystemUserModal();
                    loadSystemUsers(); // 刷新用户列表
                } else {
                    alert(`创建失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`创建失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理编辑系统用户表单提交
document.addEventListener('DOMContentLoaded', function () {
    const editSystemUserForm = document.getElementById('editSystemUserForm');
    if (editSystemUserForm) {
        editSystemUserForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitEditSystemUserBtn');
            const originalText = submitBtn.textContent;

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '更新中...';

            try {
                const formData = new FormData(this);
                const userId = formData.get('editSystemUserId');
                const data = {
                    email: formData.get('editSystemEmail'),
                    full_name: formData.get('editSystemFullName'),
                    is_active: formData.get('editSystemIsActive') === 'on',
                    is_admin: formData.get('editSystemIsAdmin') === 'on',
                    new_password: formData.get('editSystemNewPassword')
                };

                const response = await fetch(`/api/users/${userId}/update`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('用户信息更新成功！');
                    closeEditSystemUserModal();
                    loadSystemUsers(); // 刷新用户列表
                } else {
                    alert(`更新失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`更新失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 点击弹窗外部关闭弹窗
window.addEventListener('click', function (event) {
    const modals = [
        'addUserModal',
        'createDatabaseModal',
        'viewCollectionsModal',
        'editUserModal',
        'addConnectionModal',
        'editConnectionModal',
        'changePasswordModal',
        'profileModal',
        'createSystemUserModal',
        'editSystemUserModal'
    ];

    modals.forEach(modalId => {
        const modal = document.getElementById(modalId);
        if (modal && event.target === modal) {
            modal.style.display = 'none';
        }
    });
});

// 处理新增连接表单提交
document.addEventListener('DOMContentLoaded', function () {
    const addConnectionForm = document.getElementById('addConnectionForm');
    if (addConnectionForm) {
        addConnectionForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitConnectionBtn');
            const originalText = submitBtn.textContent;

            // 获取表单数据
            const formData = new FormData(this);
            const connectionData = {
                name: formData.get('connectionName').trim(),
                host: formData.get('connectionHost').trim(),
                port: parseInt(formData.get('connectionPort')),
                username: formData.get('connectionUsername').trim(),
                password: formData.get('connectionPassword'),
                auth_database: formData.get('connectionAuthDb').trim() || 'admin',
                use_ssl: formData.get('connectionSSL') === 'on',
                is_active: formData.get('connectionActive') === 'on'
            };

            // 验证必要字段
            if (!connectionData.name || !connectionData.host || !connectionData.username || !connectionData.password) {
                alert('请填写所有必要字段！');
                return;
            }

            if (connectionData.port < 1 || connectionData.port > 65535) {
                alert('端口号必须在1-65535之间！');
                return;
            }

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '创建中...';

            try {
                const response = await fetch('/api/mongo-connections', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(connectionData)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('连接创建成功！');
                    closeAddConnectionModal();
                    loadConnections(); // 刷新连接列表
                    loadConnectionOptions(); // 刷新连接选择框
                } else {
                    alert(`创建失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`创建失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});

// 处理编辑连接表单提交
document.addEventListener('DOMContentLoaded', function () {
    const editConnectionForm = document.getElementById('editConnectionForm');
    if (editConnectionForm) {
        editConnectionForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            const submitBtn = document.getElementById('submitEditConnectionBtn');
            const originalText = submitBtn.textContent;

            if (!currentEditConnectionId) {
                alert('没有选择要编辑的连接！');
                return;
            }

            // 获取表单数据
            const formData = new FormData(this);
            const connectionData = {
                name: formData.get('editConnectionName').trim(),
                host: formData.get('editConnectionHost').trim(),
                port: parseInt(formData.get('editConnectionPort')),
                username: formData.get('editConnectionUsername').trim(),
                password: formData.get('editConnectionPassword'),
                auth_database: formData.get('editConnectionAuthDb').trim() || 'admin',
                use_ssl: formData.get('editConnectionSSL') === 'on',
                is_active: formData.get('editConnectionActive') === 'on'
            };

            // 验证必要字段
            if (!connectionData.name || !connectionData.host || !connectionData.username || !connectionData.password) {
                alert('请填写所有必要字段！');
                return;
            }

            if (connectionData.port < 1 || connectionData.port > 65535) {
                alert('端口号必须在1-65535之间！');
                return;
            }

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '更新中...';

            try {
                const response = await fetch(`/api/mongo-connections/${currentEditConnectionId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(connectionData)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    alert('连接更新成功！');
                    closeEditConnectionModal();
                    loadConnections(); // 刷新连接列表
                    loadConnectionOptions(); // 刷新连接选择框
                } else {
                    alert(`更新失败: ${result.error || '未知错误'}`);
                }
            } catch (error) {
                alert(`更新失败: ${error.message}`);
            } finally {
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }
});